package dev

import (
	"encoding/json"
	"log"
	"rhelper"
)

var (
	// CONTROLLER_APP_TYPE_WIFI_PLUG_WITH_MEASURE = "switch-measure"
	DATE_UTC_FORMAT = "20060102150405"

	waitKey    = make(map[string]chan int)
	waitKeyCid = make(map[string]chan string)
	waitDevRsp = make(map[string]chan<- []byte)
)

func OnControllerMessage(msgBuf []byte) {
	var devMsg DevMsg
	err := json.Unmarshal(msgBuf, &devMsg)
	if err != nil {
		log.Println("onControllerMessage failed, json decode failed:", err)
		return
	}

	dev2User := Dev2UserMsgHead{}
	err = json.Unmarshal(devMsg.MsgBuf, &dev2User)
	if err != nil {
		log.Println("unmarshal json message head failed:", err)
		return
	}

	if dev2User.URI == "update" {
		rhelper.UpdateFlag <- devMsg.Cid
		return
	}

	//rhelper.TestChan <- 1

	onJSONMessage(dev2User, &devMsg)

}

// func updateControllerRelay(cid string, relay string) {
// 	rconn := rhelper.Pool().Get()
// 	defer rconn.Close()
// 	rconn.Do("HSET", rhelper.ControllerHash+cid, "relay", relay)
// }

func updateControllerRelayWithRunTime(cid string, msgBuf []byte) {
	type Status struct {
		Relay string `json:"relay"`
	}

	var status Status
	err := json.Unmarshal(msgBuf, &status)
	if err != nil {
		log.Println("updateControllerRelay failed, parser err: ", err)
		return
	}

	rconn := rhelper.Pool().Get()
	defer rconn.Close()
	log.Println("save", string(msgBuf))
	//_, err = rconn.Do("LPUSH", rhelper.PurifiersStatus + cid, string(msgBuf))
	rconn.Do("HSET", rhelper.ControllerHash+cid, "relay", status.Relay)
}

func SetWaitDevRsp(cid string, wait chan<- []byte) {
	_, ok := waitDevRsp[cid]
	if ok {
		log.Println("device have been wait for respone, can't set wait")
		return
	}

	waitDevRsp[cid] = wait
}

func SetWaitKey(account string, key chan int, cid chan string) {
	waitKey[account] = key
	waitKeyCid[account] = cid
}

func GetWaitKey(account string) (chan int, bool) {
	key, ok := waitKey[account]
	return key, ok
}

func DeleteWaitKey(account string) {
	delete(waitKey, account)
}

func GiveupWaitAndDiscard(cid string) {
	delete(waitDevRsp, cid)
}

func IsControllerBusy(cid string) bool {
	_, ok := waitDevRsp[cid]
	if ok {
		return true
	}
	return false
}
